#!/usr/bin/env python3
"""
直接测试有问题的视频文件
"""

import asyncio
from pathlib import Path
from app.services.video_splitter import VideoSplitter

async def test_problem_video():
    """测试有问题的视频文件"""
    
    video_path = Path("uploads/ed0df223-f7c5-4a97-9ace-f3bed83ca3a3.mp4")
    
    if not video_path.exists():
        print(f"❌ 视频文件不存在: {video_path}")
        return
    
    print(f"🧪 测试有问题的视频文件")
    print(f"📹 视频文件: {video_path}")
    print(f"📊 文件大小: {video_path.stat().st_size} bytes")
    
    splitter = VideoSplitter()
    
    try:
        # 1. 获取视频信息
        print(f"\n1️⃣ 获取视频信息...")
        video_info = await splitter._get_video_info(video_path)
        print(f"   视频时长: {video_info['duration']:.1f}秒")
        print(f"   视频分辨率: {video_info['width']}x{video_info['height']}")
        print(f"   帧率: {video_info['fps']}")
        
        # 2. 测试单个片段提取
        print(f"\n2️⃣ 测试单个片段提取...")
        
        # 创建输出目录
        video_id = video_path.stem
        segment_dir = Path("uploads/segments") / video_id
        segment_dir.mkdir(parents=True, exist_ok=True)
        
        # 测试提取第一个片段
        segment_path = segment_dir / "test_segment_000.mp4"
        
        print(f"   输出路径: {segment_path}")
        
        # 手动调用_extract_segment方法
        success = await splitter._extract_segment(
            video_path, segment_path, 0.0, 10.0  # 只提取前10秒
        )
        
        print(f"   提取结果: {'✅ 成功' if success else '❌ 失败'}")
        
        if success and segment_path.exists():
            file_size = segment_path.stat().st_size
            print(f"   文件大小: {file_size} bytes")
        else:
            print(f"   文件是否存在: {segment_path.exists()}")
        
        # 3. 测试FFmpeg命令直接执行
        print(f"\n3️⃣ 测试FFmpeg命令直接执行...")
        
        import subprocess
        
        cmd = [
            'ffmpeg', '-i', str(video_path),
            '-ss', '0', '-t', '10',
            '-c', 'copy', '-avoid_negative_ts', 'make_zero',
            '-y', str(segment_dir / "direct_test.mp4")
        ]
        
        print(f"   执行命令: {' '.join(cmd)}")
        
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
        
        print(f"   返回码: {result.returncode}")
        if result.returncode != 0:
            print(f"   stderr: {result.stderr}")
            print(f"   stdout: {result.stdout}")
        else:
            output_file = segment_dir / "direct_test.mp4"
            if output_file.exists():
                print(f"   ✅ 直接执行成功，文件大小: {output_file.stat().st_size} bytes")
            else:
                print(f"   ❌ 直接执行失败，文件不存在")
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(test_problem_video())